package com.nya.bf;

import java.util.HashMap;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.AudioManager;
import android.media.SoundPool;
import android.media.SoundPool.OnLoadCompleteListener;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.widget.TextView;

public class BurpFartActivity extends Activity implements SensorEventListener {
	 
	private SensorManager sensorManager = null;
	private volatile boolean BURP = false;
	private volatile boolean FART = false;
 
	private SoundPool soundPool;
	private AudioManager audioManager;
	private Integer burpSoundId, fartSoundId = null;
	private HashMap<Integer, Boolean> soundStatus = new HashMap<Integer, Boolean>();
	private Vibrator vib;
	private long fartPattern[] = { 200, 100, 50, 75,50,50};

	// Dialogs
	private static final int DIALOG_QUIT = 0;
	private static final int DIALOG_ABOUT = 1;
	
	Dialog dialog;
	
	public boolean getBurp() {
		return BURP;
	}
	
	public boolean getFart() {
		return FART;
	}
	 
    // Called when the activity is first created.
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
    	setContentView(R.layout.main);

    	// Get a reference to a SensorManager
        sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        
        // Application's default volume control
    	this.setVolumeControlStream(AudioManager.STREAM_MUSIC);  
        
        // Getting the user sound settings
		audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
        
        // Load the sound
		soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
		soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
			public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
				soundStatus.put(sampleId, true);
			}
		});
		burpSoundId = soundPool.load(this, R.raw.burp, 1);
		fartSoundId = soundPool.load(this, R.raw.fart, 1);
		soundStatus.put(burpSoundId, false);
		soundStatus.put(fartSoundId, false);
		
		vib = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
    }
    
    @Override
    protected void onResume() {
    	super.onResume();
    	// Register this class as a listener for the accelerometer sensor
    	sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
    }

    @Override
    protected void onPause() {
    	super.onPause();
    	// Unregister the listener
    	sensorManager.unregisterListener(this);
    }
   
    // This method will update the UI on new sensor events
    public void onSensorChanged(SensorEvent sensorEvent) {
    	synchronized (this) {
    		if (sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
    			
    			float actualVolume = (float) audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
    			float maxVolume = (float) audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
    			float volume = actualVolume / maxVolume;
    			
    			performBurpFart(sensorEvent.values, volume);
    		}
    	}
    }
    
    // Not implemented
    public void onAccuracyChanged(Sensor arg0, int arg1) {
    }
    
    public void performBurpFart(float[] values, float volume) {
    	
    	if(values[1] > 5 && !BURP) {
			// burp
			BURP = true;
			
			if (soundStatus.get(burpSoundId))
				soundPool.play(burpSoundId, volume, volume, 1, 0, 1f);
			
            FART = false;
		}
		else if(values[1] < -5 && !FART) {
			// fart
			FART = true;
			
			if (soundStatus.get(fartSoundId))
				soundPool.play(fartSoundId, volume, volume, 1, 0, 1f);
			
			vib.vibrate(fartPattern, -1);

            BURP = false;
		}
    }
    
    /**
	 * onCreateDialog
	 * dialogs consisting of:
	 *  - menu selection quit prompt (DIALOG_QUIT)
	 *  - menu selection about prompt (DIALOG_ABOUT)
	 */
    @Override
    protected Dialog onCreateDialog(int id) {
        
        switch(id) {
        // Quit program
        case DIALOG_QUIT:
        	AlertDialog.Builder builder = new AlertDialog.Builder(this);
        	builder.setMessage("Are you sure you want to exit?");
        	builder.setCancelable(false);
        	// Quit Yes
        	builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
        		public void onClick(DialogInterface dialog, int id) {
    	        	   finish();
    	           }
    	       });
        	// Quit No
        	builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
        	           public void onClick(DialogInterface dialog, int id) {
        	        	   dialog.cancel();
        	           }
        	       });
        	dialog = builder.create();
            break;
        // About box
        case DIALOG_ABOUT:

    		dialog = new Dialog(this) {
    			
    			// Close the dialog if the screen is touched
    			@Override
    			public boolean onTouchEvent(MotionEvent event) {
    				switch (event.getAction()) {
    				case MotionEvent.ACTION_DOWN:
    					this.cancel();
    					break;
    				}
                    return true;
                }
    		};

        	dialog.setContentView(R.layout.about_dialog);
        	dialog.setTitle(R.string.about_title);

        	TextView text = (TextView) dialog.findViewById(R.id.text);
        	text.setText(R.string.about_message);
        	
            break;
        default:
            dialog = null;
        }
        return dialog;
    }
    
    /**
	 * onCreateOptionsMenu
	 * Creates of options in the menu (context click button on device)
	 */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.option_menu, menu);
        return true;
    }

    /**
	 * onOptionsItemSelected
	 * Presents the user with the options available when clicking the menu
	 */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        
    	switch (item.getItemId()) {
    	case R.id.about:
            // show about screen
        	showDialog(DIALOG_ABOUT);
            return true;
        case R.id.quit: 
        	// Exit application
            // Prompt are you sure ?
        	showDialog(DIALOG_QUIT);
        	
            return true;
        }
        
        return false;
    }
}